var express = require('express')
var router = express.Router()
const query = require('../pool')

// 获取日历事件
router.get('/getCalendarEvents', async (req, res) => {
  const [err, data] = await query(`SELECT * FROM HopeTravel.calendar ORDER BY date DESC`)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data: data
    })
  }
})

// 更新日历事件
router.post('/updateCalendarEvent', async (req, res) => {
  const id = req.body.id ? req.body.id : '';
  const title = req.body.title ? req.body.title : '';
  const des = req.body.des ? req.body.des : '';
  const date = req.body.date ? req.body.date : '';
  const owner = req.body.owner ? req.body.owner : '';
  const sql = `UPDATE HopeTravel.calendar
    SET title='${title}', des='${des}', date='${date}', owner='${owner}' WHERE id='${id}'`;
  const [err, data] = await query(sql);
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data: '更新成功'
    })
  }
})

// 新增日历事件
router.post('/addCalendarEvent', async (req, res) => {
  const title = req.body.title ? req.body.title : '';
  const des = req.body.des ? req.body.des : '';
  const date = req.body.date ? req.body.date : '';
  const owner = req.body.owner ? req.body.owner : '';
  const sql = `INSERT INTO HopeTravel.calendar
(title, des, date, owner)
VALUES('${title}', '${des}', '${date}', '${owner}')`
  const [err, data] = await query(sql);
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data: '添加成功'
    })
  }
})

// 获取歌曲
router.get('/getSongs', async (req, res) => {
  const [err, data] = await query(`SELECT * FROM HopeTravel.music ORDER BY sort DESC`)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    const finalSongs = data.map(item => {
      return {
        ...item,
        src: `http://music.163.com/song/media/outer/url?id=${item.sId}.mp3`
      }
    })
    res.send({
      code: 0,
      data: finalSongs
    })
  }
})

module.exports = router
